package com.mxdx.edu.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.util.StringUtils;

/**
 * 图片验证码生成接口
 * 
 * @author WangYuan
 * @since 2016年5月31日 下午4:09:24
 */

@Controller
@RequestMapping("/public/api/ImgCode")
public class CaptchaController extends BaseController {

    @Resource
    private DefaultKaptcha producer;

    private AppLogger logger = new AppLogger(CaptchaController.class);

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> kaptcha(HttpServletRequest request) {
        logger.entry(request.getRemoteAddr(), "kaptcha");
        Map<String, Object> retMap = new HashMap<>();
        Map<String, Object> logMap = new HashMap<>();
        ApiResult<Map<String, Object>> resRet = new ApiResult<>();

        String uuid = StringUtils.getUUId();
        String capText = producer.createText();
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            logMap.put("uuid", uuid);
            logMap.put("code", capText);

            BufferedImage image = producer.createImage(capText);
            ImageIO.write(image, "jpg", out);
            byte[] imageByte = out.toByteArray();
            redisUtil.set(String.format("imageCode_%s", uuid), capText, 60);

            retMap.put("uuid", uuid);
            retMap.put("imgStr", Base64.encodeBase64String(imageByte));
        } catch (Exception e) {
          dealException(ErrorEnums.SYSTEM_ERROR, e, resRet, logger);
        }
        return retMap;
    }
}
